package com.ce.pms.custservice.service;

import static org.junit.Assert.assertEquals;

import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashSet;
import java.util.Set;

import junit.framework.Assert;

import org.apache.log4j.Logger;
import org.hibernate.SQLQuery;
import org.junit.Test;

import com.ce.pms.DBUnitTool;
import com.ce.pms.base.dao.IPmsBaseHibernateDao;
import com.ce.pms.common.model.SysrefcodeDO;
import com.ce.pms.custservice.dao.ICustServiceEventDao;
import com.ce.pms.custservice.dao.IReturnVisitRecordDao;
import com.ce.pms.custservice.model.CustServiceEventDO;
import com.ce.pms.custservice.model.QuestionAndAnswer;
import com.ce.pms.custservice.model.ReturnVisitRecordDO;
import com.ce.pms.custservice.vo.AbstractQuestionaireVO;
import com.ce.pms.custservice.vo.CustServiceEventVO;
import com.ce.pms.custservice.vo.QuestionAndAnswerVO;
import com.ce.util.BlankUtil;
import com.sitechasia.webx.core.utils.base.PopulateUtil;


public class ReturnVisitServiceImplT extends DBUnitTool {
	private static final Logger logger=Logger.getLogger(ReturnVisitServiceImplT.class);
	private IReturnVisitService returnVisitService;
	private IReturnVisitRecordDao returnVisitRecordDao;
	private ICustServiceEventDao custServiceEventDao;
	private IEventManageService eventManageService;
	/* (non-Javadoc)
	 * @see com.ce.pms.DBUnitTool#setUp()
	 */
	@Override
	public void setUp() throws Exception {
		// TODO Auto-generated method stub
		super.setUp();
		initReturnVisit();

		Assert.assertNotNull(returnVisitService);
		Assert.assertNotNull(returnVisitRecordDao);
		Assert.assertNotNull(custServiceEventDao);
		Assert.assertNotNull(eventManageService);
	}

	/* (non-Javadoc)
	 * @see com.ce.pms.DBUnitTool#tearDown()
	 */
	@Override
	public void tearDown() throws Exception {
		// TODO Auto-generated method stub
		super.tearDown();
		returnVisitService = null;
		returnVisitRecordDao =  null;
		custServiceEventDao = null;
		eventManageService = null;
	}

	private void initReturnVisit(){
		if(returnVisitService == null){
			returnVisitService = (IReturnVisitService)this.applicationContext.getBean("returnVisitService");
		}
		if(returnVisitRecordDao == null){
			returnVisitRecordDao = (IReturnVisitRecordDao)this.applicationContext.getBean("returnVisitRecordDao");
		}
		if(custServiceEventDao == null){
			custServiceEventDao = (ICustServiceEventDao)this.applicationContext.getBean("custServiceEventDao");
		}
		if(eventManageService == null){
			eventManageService = (IEventManageService)this.applicationContext.getBean("eventManageService");
		}
	}

	/**
	 * 功能描述:处理提交得答案<br>
	 * 页面有多个回访内容，要求对每个回访内容处理。所以对页面得输入框得name进行了一些处理。
	 * 回访ID:   没有任何要求,回访答案：回访ID + “_answer”; 回访备注: 回访ID + “_remark”
	 */
	private Set<QuestionAndAnswerVO> processAnswer(){
		String[] returnVisitItems = new String[]{"1","2","6"};
		if(returnVisitItems == null || returnVisitItems.length ==0) return null;

		Set<QuestionAndAnswerVO> answerSet = new HashSet<QuestionAndAnswerVO>();
		QuestionAndAnswerVO answerTemp = null;
		for(String item : returnVisitItems){
			String answer = item + "_answer";
			if(BlankUtil.isBlank(answer)) continue;

			answerTemp = new QuestionAndAnswerVO();
			answerTemp.setReturnVisitItemID(Long.valueOf(item)); //回访项目
			answerTemp.setAnswer(answer);

			String remark = item + "_remark";
			answerTemp.setRemark(remark);
			answerSet.add(answerTemp);
		}
		return answerSet;
	}


	/**
	 * 事件状态:已完成
	 */
	public static final String EVENT_STATUS_COMPLETE_CODE = "003";
	/**
	 * 事件状态:待归档
	 */
	public static final String EVENT_STATUS_ARCHIVING_CODE = "004";
	/**
	 * 回访状态:已回访
	 */
	public static final String RETURN_VISIT_STATUZ_COMPLETE_CODE = "002";


	/***
	 * 功能描述:  私有方法，设置事件值<br>
	 * @param custServEventVO
	 * @return
	 * Create author:高嵩 <br>
	 * Create on:2008-12-30  <br>
	 * Edit author:  <br>
	 * Edit on:    <br>
	 * Why:     <br>
	 */
	private CustServiceEventVO getCustServiceEventVO(CustServiceEventVO custServEventVO){

		custServEventVO.setContact("联系人");
		custServEventVO.setEventContent("事件内容回访测试");
		custServEventVO.setValidity("001");//有效性:001有效;002待定;000无效
		custServEventVO.setCreator(new Long(1));//创建人
		//custServEventVO.setModifier(new Long(2));//修改人
		custServEventVO.setHouseKeyword(new Long(6));//房号主键

		custServEventVO.setEventRegionKeyword(new Long(2));//事件区域
		custServEventVO.setCustServEventKindKeyword(new Long(1));//事件类型
		custServEventVO.setEventNatureKeyword(new Long(1));//客户事件性质
		custServEventVO.setSeriousDegreeKeyword(new Long(1));//时间严重程度ID
		custServEventVO.setEmergencyDegreeKeyword(new Long(1));//紧急程度
		custServEventVO.setAppointment("2009-01-11 08:44:43");//预约时间

		return custServEventVO;
	}


	/***
	 * 功能描述: 私有方法，设置值<br> <br>
	 * @param questionaireVO
	 * @return
	 * Create author:高嵩 <br>
	 * Create on:2009-1-6  <br>
	 * Edit author:  <br>
	 * Edit on:    <br>
	 * Why:     <br>
	 */
	private AbstractQuestionaireVO getQuestionaireVO(AbstractQuestionaireVO questionaireVO){
		CustServiceEventVO custServEventVO = new CustServiceEventVO();
//		增加客服事件记录
		this.eventManageService.addCustEvent(this.getCustServiceEventVO(custServEventVO));

		CustServiceEventDO custServiceEventDODB = this.custServiceEventDao.findById(custServEventVO.getKeyword());

		//增加成功
		assertEquals(custServEventVO.getKeyword(),custServiceEventDODB.getKeyword());
		//设置事件状态为已完成，以便做回访操作
		custServiceEventDODB.setEventStatuz(EVENT_STATUS_COMPLETE_CODE);
		this.custServiceEventDao.updateObject(custServiceEventDODB);
		Assert.assertEquals(EVENT_STATUS_COMPLETE_CODE, custServiceEventDODB.getEventStatuz());


		questionaireVO.setCustomerServiceEventID(custServiceEventDODB.getKeyword());//设置事件ID
		questionaireVO.setReturnVisitWayID(new Long(1));//回访方式ID
		questionaireVO.setClient("联系人Aaaa");
		questionaireVO.setHouseID(new Long(3));
		questionaireVO.setHouseNumber("1-A");
		questionaireVO.setFullAddress("新猪院");
		questionaireVO.setRecorder("回访人");
		try {
			questionaireVO.setRecordTime(new SimpleDateFormat("yyyy-MM-dd").parse("2009-01-01"));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		questionaireVO.setSummarize("回访情况概述测试");

		Set<QuestionAndAnswerVO> answerSet = processAnswer();
		questionaireVO.setQuestionAndAnswerSet(answerSet);

		questionaireVO.setCreator(new Long(1));
		questionaireVO.setCustomerServiceEventID(custServiceEventDODB.getKeyword());
		return questionaireVO;
	}

	/***
	 * 功能描述: 获取最后插入的数据ID主键 <br>
	 * @return
	 * Create author:高嵩 <br>
	 * Create on:2009-1-6  <br>
	 * Edit author:  <br>
	 * Edit on:    <br>
	 * Why:     <br>
	 */
	private Long getLastInsertID(){
		IPmsBaseHibernateDao pmsBaseHibernateDao =  (IPmsBaseHibernateDao)applicationContext.getBean("pmsBaseHibernateDao");
		String sql = "SELECT LAST_INSERT_ID()";
		SQLQuery sqlQuery=pmsBaseHibernateDao.createSQLQuery(sql);
		Object temp = sqlQuery.uniqueResult();
		Long lastId = temp==null?null:((BigInteger)temp).longValue();
		logger.debug("最后插入的数据ID: "+lastId);
		Assert.assertNotNull(lastId);
		return lastId;
	}


	/***
	 * 功能描述: 测试新增回访 <br>
	 *
	 * Create author:高嵩 <br>
	 * Create on:2009-1-6  <br>
	 * Edit author:  <br>
	 * Edit on:    <br>
	 * Why:     <br>
	 */

	@Test
	public void testAddQuestionair(){
		System.out.println("---------------------------测试新增回访开始----------------------------------");
		logger.debug("---------------------------测试新增回访开始debug----------------------------------");
		logger.info("---------------------------测试新增回访开始info----------------------------------");
		AbstractQuestionaireVO questionaireVO = new AbstractQuestionaireVO();
		questionaireVO = getQuestionaireVO(questionaireVO);
		returnVisitService.addQuestionair(questionaireVO.getCustomerServiceEventID(), questionaireVO);

		Long questionAndAnswerID = getLastInsertID();//回访问卷ID

		IPmsBaseHibernateDao pmsBaseHibernateDao =  (IPmsBaseHibernateDao)applicationContext.getBean("pmsBaseHibernateDao");
		String sql = "SELECT QUESTIONAIRE_ID FROM  CE_QUESTION_AND_ANSWER where QUESTION_AND_ANSWER_ID= ?";
		SQLQuery sqlQuery =  pmsBaseHibernateDao.createSQLQuery(sql);
		sqlQuery.setLong(0, questionAndAnswerID);
		Object temp = sqlQuery.uniqueResult();


		Long returnVisitID = temp==null?null:((BigInteger)temp).longValue();
		Assert.assertNotNull(returnVisitID);


		ReturnVisitRecordDO  returnVisitRecordDO = this.returnVisitRecordDao.findById(returnVisitID);
		Assert.assertNotNull(returnVisitRecordDO);
		//测试增加成功
		Assert.assertEquals(returnVisitID, returnVisitRecordDO.getKeyword());

		CustServiceEventDO custServiceEventDO = this.custServiceEventDao.findById(questionaireVO.getCustomerServiceEventID());
		Assert.assertNotNull(custServiceEventDO);

		String eventStatus = custServiceEventDO.getEventStatuz();
		//如果事件状态为"已完成"或者是"待归档"状态
		if(EVENT_STATUS_COMPLETE_CODE.equals(eventStatus) || EVENT_STATUS_ARCHIVING_CODE.equals(eventStatus)){
			Assert.assertEquals(custServiceEventDO.getReturnVisitStatuz(), RETURN_VISIT_STATUZ_COMPLETE_CODE);
		}
		//删除问答卷
		sql = "delete from CE_QUESTION_AND_ANSWER where QUESTIONAIRE_ID = ?";
		sqlQuery = pmsBaseHibernateDao.createSQLQuery(sql);
		sqlQuery.setLong(0, returnVisitRecordDO.getKeyword());
		sqlQuery.executeUpdate();

		//删除回访表
		this.returnVisitRecordDao.deleteObjectById(returnVisitRecordDO.getKeyword());
		returnVisitRecordDO = this.returnVisitRecordDao.findById(returnVisitRecordDO.getKeyword());
		Assert.assertNull(returnVisitRecordDO);

		//删除事件
		//returnVisitRecordDO.getCustomerServiceEventDO().getKeyword()
		this.custServiceEventDao.deleteObjectById(questionaireVO.getCustomerServiceEventID());
		custServiceEventDO = this.custServiceEventDao.findById(questionaireVO.getCustomerServiceEventID());
		Assert.assertNull(custServiceEventDO);

	}


	/***
	 * 功能描述:  测试判断是否允许作废回访
	 * @param   回访问卷ID
	 * @return
	 * Create author:高嵩 <br>
	 * Create on:2009-1-6  <br>
	 * Edit author:  <br>
	 * Edit on:    <br>
	 * Why:     <br>
	 */
	//@Test
	public void testIsAllowSetAsideReturnVisit(){

		ReturnVisitRecordDO returnVisitRecordDO = this.returnVisitRecordDao.findById(new Long(119));
		Assert.assertNotNull(returnVisitRecordDO);
		Assert.assertNotNull(returnVisitRecordDO.getKeyword());

		Assert.assertTrue(this.returnVisitService.isAllowSetAsideReturnVisit(returnVisitRecordDO.getKeyword()));


//		当数据状态为作废时,则抛出异常
		returnVisitRecordDO.setValidity(SysrefcodeDO.CONSTANTS_DIGITAL_ZERO);
		this.returnVisitRecordDao.saveObject(returnVisitRecordDO);
		Assert.fail("已作废回访，不能作废了");this.returnVisitService.isAllowSetAsideReturnVisit(returnVisitRecordDO.getKeyword());

	}

	/**
	    * 功能描述: 测试作废访问登记  <br>
	    * Create on:2008-12-31  <br>
	    * Edit author:  <br>
	    * Edit on:    <br>
	    * Why:     <br>
	    */

	public void testSetAside(){

	}



	/**
	    * 功能描述: 根据ID查询回访登记信息  <br>
	    * Create author:高嵩<br>
	    * Create on:2008-12-31  <br>
	    * Edit author:  <br>
	    * Edit on:    <br>
	    * Why:     <br>
	    */
   public void testGetReturnVisitRecordByID(){

   }




//   Vector lineObj;
//   ReturnVisitServiceImplT() {
//       lineObj = new Vector();
//   }
///**
//* 将值添加到 Vector 对象.
//*/
//
//   void add(final String [] input) {
//       for (int ctr = 0; ctr < input.length; ctr++) {
//           lineObj.addElement(input[ctr]);
//       }
//   }
//
///**
//* 反转并显示 Vector 对象的值.*/
//
//   void reverse() {
//
//        System.out.println("\n*************************");
//        System.out.println("倒序显示的内容");
//        System.out.println("*************************");
//
//        for (int ctr = lineObj.size() - 1; ctr >= 0; ctr--) {
//            System.out.println(lineObj.elementAt(ctr));
//        }
//   }
//
///**
//* 倒序存储值.*/
//
//   void sort() {
//       System.out.println("***********************************");
//       System.out.println("按降序分类的内容");
//       System.out.println("***********************************");
//
//       while (lineObj.size() != 0) {
//           String displayLine = (String) (lineObj.elementAt(0));
//           int linenumber = 0;
//            for (int ctr = 1; ctr < lineObj.size(); ctr++)
//            {/*compare
//int compare(T o1,
//           T o2)比较用来排序的两个参数。随第一个参数小于、等于或大于第二个参数而分别返回负整数、零或正整数。
//*/
//               if (((String) lineObj.elementAt(ctr)).compareTo(displayLine) > 0) {
//                    displayLine = (String) lineObj.elementAt(ctr);
//                    linenumber = ctr;
//                }
//            }
//        System.out.println(displayLine);
//
//       }
//    }
//   public static void main(String[] args) {
//	   ReturnVisitServiceImplT vectorLineObj = new ReturnVisitServiceImplT();
//	   String[] name=new String[2];
//	   name[0]="human";
//	   name[1]="增长率";
//       vectorLineObj.add(name);
//       vectorLineObj.reverse();
//      // vectorLineObj.sort();
//   }
}






